<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 前台控制器类
 */
class MY_Controller extends CI_Controller {
	protected $cfg;
	protected $res;

	//用户信息
	protected $member;

	function __construct()
	{
		parent::__construct();
		$this->load->model('Member_model');
		$this->member =& $this->Member_model;
		$this->Cache_model->setLang($this->input->get());
		$this->Lang_model->loadLang('front',$this->Cache_model->currentLang);
		$this->load->helper('tags');
		$this->cfg = $this->Cache_model->loadConfig();

	}

	/**
	 * 获取最新注册会员
	 */
	function getLatest($limit=6){
		//$sql = $this->Data_model->db->_compile_select();
		$where=array();
		/*$this->Data_model->db->select('m.mid,m.mgroup,m.mname,m.mnick,m.avatar,m.goodnum,m.watchnum,m.viewnum,m.commnum,m.shares,md.view,max(md.uptime) as uptime,md.title,md.content')->from('member m')->join('member_data md','md.mid=m.mid','left');
		$where['md.isdefault']=1;
		$mlist = $this->Data_model->getData($where,'md.uptime DESC,m.mid DESC',0,$limit);*/

		$this->Data_model->db->select('m.mid,m.mgroup,m.mname,m.mnick,m.avatar,mw.id,mw.image,mw.puttime,mw.title,mw.summary')->distinct('m.mid')->from('member m')->join('works mw','mw.mid=m.mid','left');
		$mlist = $this->Data_model->getData($where,'mw.puttime DESC,m.mid DESC',$limit,0);
		//echo $this->Data_model->db->last_query();
		foreach ($mlist as $key => $value) {
			if(empty($value['mnick'])){
				$mlist[$key]['mnick']=$value['mname'];
			}
			$mlist[$key]['puttime']=date('Y.m.d',$value['puttime']);
			if($this->member->mid==$value['mid']){
				$mlist[$key]['href']=site_url('member/work/'.$value['id']);
				$mlist[$key]['spaceurl']=site_url('member');
			}else{
				$mlist[$key]['href']=site_url('space/work/'.$value['mid'].'/'.$value['id']);
				$mlist[$key]['spaceurl']=site_url('space/'.$value['mid']);
			}
			
		}

		return $mlist;

	}

	//获取个人对作品列表的赞，关注情况
	function getUnionData($lists){
		$ud=array(
			'goods'=>array(),
			'watchs'=>array()
			);
		if($this->member->mid){
			$ids=array();
			foreach ($lists as $key => $value) {
				$ids[]=$value['id'];
			}
			$ud['goods']=$this->getKeyArray($ids,'work_good');
			$ud['watchs']=$this->getKeyArray($ids,'work_watch');
		}
		return $ud;
	}

	/**
	 * 将数据转换成id=>值对
	 */
	function getKeyArray($ids,$table){
		$uarr=$this->Data_model->db
			->where(array('mid'=>$this->member->mid))
			->where_in('wid',$ids)
			->get($table)
			->result_array();
		$udata=array();
		foreach ($uarr as $key => $value) {
			$udata[$value['wid']]=$value['mid'];
		}
		return $udata;
	}

	/**
	 * 获取图像，评论等扩展信息
	 */
	function getExtends(&$worklist,$num=0,$types=''){
		if(empty($types)){
			$types=array('image','comment');
		}
		if(in_array('image', $types)){
			foreach ($worklist as $key => $value) {
				$worklist[$key]['images']=$this->Data_model->getData(array('wid'=>$value['id']),'id ASC',0,$num,'work_image');
			}
		}
		if(in_array('comment', $types)){
			foreach ($worklist as $key => $value) {
				$where=array('wc.wid'=>$value['id'],'wc.reid'=>0);
				$this->Data_model->db->from('work_comm wc')->select('wc.*,m.mname,m.mnick,m.avatar')->join('member m','m.mid=wc.mid','left');
				$worklist[$key]['comments']=$this->Data_model->getData($where,'wc.id DESC',0,$num);	
				//回复
				foreach($worklist[$key]['comments'] as $k=> $val){
					$where=array('wid'=>$val['wid'],'reid'=>$val['id']);
					$this->Data_model->db->from('work_comm wc')->select('wc.*,m.mname,m.mnick,m.avatar')->join('member m','m.mid=wc.mid','left');
					$remsglist=$this->Data_model->getData($where,'wc.id DESC',0,1);	
					$worklist[$key]['comments'][$k]['remsglist']=array();
					if(count($remsglist)>0){
						$worklist[$key]['comments'][$k]['remsglist']=$remsglist[0];
					}	
				}			
			}
		}
		return $worklist;
	}

	/**
	 * 显示模板输出
	 */
	function view($tpl=null,$res=array()){

		if(!isset($this->cfg['seo_title'])){
			$this->seo();
		}
		$this->res = array(
				'tpl'=>$tpl,
				'currentcolumn'=>'',
				'member'=>$this->member,
				'config'=>$this->cfg,
				'currentLang'=>$this->Cache_model->currentLang,
				'langurl'=>$this->Cache_model->langurl,
		);
		$this->load->setPath($this->cfg['site_template']);
		if(!empty($res))$this->res=array_merge($this->res,$res);
		if(empty($tpl)){
			$tpl=$this->uri->segment(1).'_'.$this->uri->segment(2);
		}
		$this->load->view($tpl,$this->res);

	}

	/**
	 * 记录来源页面，以备登录，注册等返回使用
	 */
	protected function recordback(){
		$back=$this->input->server('HTTP_REFERER');
		if(!empty($back) && strcmp(site_url(''),substr($back, 0, strlen(site_url(''))))==0){
			$this->session->set_userdata('backurl',$back);
		}
	}
	/**
	 * 获取记录的返回页面
	 */
	protected function getback($del=FALSE,$dft='home'){
		$back=$this->session->userdata('backurl');
		if($del){
			$this->delback();
		}
		if(empty($back)){
			return site_url($dft);
		}
		return $back;
	}
	/**
	 * 清除记录的返回页面
	 */
	protected function delback(){
		$this->session->unset_userdata('backurl');
	}

	//显示提示信息页
	function showMessage($title,$content='',$redirects='',$script=''){
		if(!is_array($redirects)){
			if(empty($redirects)){
				$redirects=array(
					array('url'=>'/','name'=>'返回首页')
				);
			}else{
				$redirects=array(
					array('url'=>$redirects,'name'=>'返回')
				);
			}
		}elseif(!is_array($redirects[0])){
			$redirects=array($redirects);
		}
		$this->view('message',array(
			'msgtitle'=>$title,
			'msgcontent'=>$content,
			'redirects'=>$redirects,
			'script'=>$script
			));
	}

	/**
	 * SEO信息
	 */
	protected function seo($title='',$keyword='',$desc=''){
		$this->cfg['seo_title'] = empty($title)?$this->cfg['site_title']:$title;
		$this->cfg['seo_keywords'] = empty($keyword)?$this->cfg['site_keywords']:$keyword;
		$this->cfg['seo_description'] = empty($desc)?$this->cfg['site_description']:$desc;
	}

	/**
	 * 检查是否登录
	 * @return TRUE/FALSE
	 */
	protected function checkLogin(){
		return $this->member && $this->member->isLogin();
	}

	/**
	 * 检查是否登录，并且根据请求信息输出Ajax或直接跳转
	 */
	protected function needLogin($redirect='auth/login'){
		if(!$this->checkLogin()){
			if($this->input->is_ajax_request()){
				$this->session->set_userdata('backpage',$this->input->server('HTTP_REFERER'));
				show_jsonmsg(array(
					'errorcode'=>4,
					'error'=>'此操作需要登录',
					'script'=>'$(\'#ajaxlogin\').trigger(\'click\');'
					//'url'=>site_url('auth/login')
					));
			}else{
				$this->session->set_userdata('backpage',current_url());
				redirect($redirect);
			}
		}
	}

	/**
	 * 通用的发送Email函数
	 * CI自有Email类莫名其妙无响应，因此使用第三方类发送邮件
	 */
	protected function sendMail($info,$dbg=false){
		/*$emailcfg=$this->Cache_model->loadConfig('mail');
		$this->load->library('Mailsmtp');
		$cfg=array(
			'protocol'=>$emailcfg['mail_type'],
			'charset'=>'utf-8',
			'auth'=>true,
			'mailtype'=>isset($info['type'])?$info['type']:'html',
			'smtp_host'=>$emailcfg['smtp_host'],
			'smtp_user'=>$emailcfg['smtp_user'],
			'smtp_pass'=>$emailcfg['smtp_pass']
			);
		if(!empty($emailcfg['smtp_port'])){
			$cfg['smtp_port']=$emailcfg['smtp_port'];
		}

	    if($dbg)$this->mailsmtp->debug=true;
		$this->mailsmtp->initialize($cfg);
	    $this->mailsmtp->sendmail($info['email'],$emailcfg['smtp_sendmail'],$info['title'],$info['content']);*/
		
		$emailcfg=$this->Cache_model->loadConfig('mail');
		$this->load->library('email');            //加载CI的email类  
          
        //以下设置Email参数  
        $config['protocol'] = $emailcfg['mail_type'];   
        $config['smtp_host'] =  $emailcfg['smtp_host'];  
        $config['smtp_user'] = $emailcfg['smtp_user'];   
        $config['smtp_pass'] = $emailcfg['smtp_pass'];  
        $config['smtp_port'] = $emailcfg['smtp_port'];    
        $config['charset'] = 'utf-8';  
        $config['wordwrap'] = TRUE;  
        $config['mailtype'] = 'html';  
		$config['newline'] = "\r\n";
		$config['crlf'] = "\r\n";
        $this->email->initialize($config);              
          
        //以下设置Email内容  
        $this->email->from($emailcfg['smtp_sendmail'], $emailcfg['smtp_user']);  
        $this->email->to($info['email']);  
        $this->email->subject($info['title']);  
        $this->email->message($info['content']);   
  
        $this->email->send();  
  
       // $this->email->print_debugger();
	}
	
	/**
	 * 获取广告
	 * @return TRUE/FALSE
	 */
	protected function getad($positon){
		switch ($positon){
			case 'home':
			 $adinfo=$this->Data_model->db->select('id,thumb,url,title')->from('slide');
			 $adinfo=$this->Data_model->getData(array('type'=>5,'status'=>1),'id DESC',1,0);	
			break;	 
		}
		return  $adinfo;
			
	}
}

/**
 * 后台控制器类
 */
class SU_Controller extends CI_Controller {

	//用户信息
	protected $user;

	function __construct()
	{
		
		parent::__construct();
		$this->Lang_model->loadLang('admin');
		$this->load->model('Purview_model');
		$this->load->model('Cache_model');

	}

	function view($tpl=null,$res=array()){

		$this->res = array(
				'tpl'=>$tpl,
				'user'=>$this->user,
		);
		if(!empty($res))$this->res=array_merge($this->res,$res);
		if(empty($tpl)){
			$tpl=$this->uri->segment(1).'_'.$this->uri->segment(2);
		}
		$this->load->view($tpl.'.php',$this->res);

	}

	protected function checkLogin(){
		$uid=$this->session->userdata('uid');
		return !empty($uid);
	}

	protected function needLogin($redirect='login'){
		if(!$this->checkLogin()){
			if($this->input->is_ajax_request()){
				$this->session->set_userdata('ubackpage',$this->input->server('HTTP_REFERER'));
				show_jsonmsg(array(
					'errorcode'=>101,
					'error'=>'此操作需要登录',
					'url'=>site_aurl($redirect)
					));
			}else{
				$this->session->set_userdata('ubackpage',current_url());
				redirect($redirect);
			}
		}
	}
}